package com.cskaoyan.controller;

import com.cskaoyan.annotation.LogRecord;
import com.cskaoyan.bean.AdminInfoBean;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.InfoData;
import com.cskaoyan.bean.LoginUserData;
import com.cskaoyan.bean.po.MarketAdmin;
import com.cskaoyan.config.shiro.MallToken;
import com.cskaoyan.service.InfoService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
@RestController
@RequestMapping("admin/auth")
public class AuthController {

    @Autowired
    InfoService infoService;


    /**
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) {
        String username = (String) map.get("username");
        String passwordOld = (String) map.get("password");
        String password = DigestUtils.md5DigestAsHex(passwordOld.getBytes());
        System.out.println(password);
        // 将当前用户变为登陆的状态
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(new MallToken(username, password,"admin"));
            // 登录之后就可以通过subject来获得信息了
            boolean authenticated = subject.isAuthenticated();
            System.out.println("authenticated = " + authenticated);


            // 下面这部分值应该来源于数据库 → 要知道用户信息principal
            // 你在realm的doGetAuthorizationInfo中的第一个参数放入的是什么，取出的就是什么
            MarketAdmin primaryPrincipal = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
            // 根据marketAdmin的信息来完善下面的信息

            LoginUserData loginUserData = new LoginUserData();
            AdminInfoBean adminInfo = new AdminInfoBean();
            adminInfo.setAvatar(primaryPrincipal.getAvatar());
            adminInfo.setNickName(primaryPrincipal.getUsername());
            loginUserData.setAdminInfo(adminInfo);
            // loginUserData.setToken("c4d988f3-e4c5-4e46-b6ce-13b9e008ea20");
            String id = (String) subject.getSession().getId();
            loginUserData.setToken(id);
            return BaseRespVo.ok(loginUserData);
        } catch (AuthenticationException e) {
            return BaseRespVo.unlogin();
        }
    }

    // http://localhost:8083/admin/auth/logout
    // response:{"errno":0,"errmsg":"成功"}
    @PostMapping("logout")
    public BaseRespVo logout() {
        BaseRespVo baseRespVo = new BaseRespVo();
        baseRespVo.setErrmsg("成功");
        baseRespVo.setErrno(0);
        return baseRespVo;
    }

    @RequestMapping("info")
    public BaseRespVo info(String token) {
        Subject subject = SecurityUtils.getSubject();
        InfoData infoData = new InfoData();
        if (subject.isAuthenticated()) {
            MarketAdmin primaryPrincipal = (MarketAdmin) subject.getPrincipals().getPrimaryPrincipal();
            infoData.setName(primaryPrincipal.getUsername());
            //根据primaryPrincipal做查询
            infoData.setAvatar(primaryPrincipal.getAvatar());
            ArrayList<String> roles = new ArrayList<>();
            //
            Integer[] roleIds = primaryPrincipal.getRoleIds();
            ArrayList<String> perms = new ArrayList<>();
            for (Integer roleId : roleIds) {
                List<String> list1 = infoService.queryRolesName(roleId);
                roles.addAll(list1);
                List<String> list = infoService.queryPermission(roleId);
                perms.addAll(list);
            }
            infoData.setRoles(roles);
            infoData.setPerms(perms);
        }
        //根据marketAdmin查询对应的信息

        //开发完shiro之后，再整合
        return BaseRespVo.ok(infoData);
    }

}
